from flask import Flask
from flask import request
import RSAsign as rsasign


app = Flask(__name__)


@app.route('/')
def index():
    return 'Hello,This is a JetBrains License Server!'

@app.route('/rpc/ping.action')
def ping():
    salt = ''
    if request.method == 'POST':
        salt = request.form.get('salt')
    if request.method == 'GET':
        salt = request.args.get('salt')

    if salt == None or salt == '':
        return 'error!'
    else:
        xmlContent = '<PingResponse><message></message><responseCode>OK</responseCode><salt>' + salt + '</salt></PingResponse>'
        xmlSignature = rsasign.sign(xmlContent)
        body = '<!-- ' + xmlSignature + ' -->\n' + xmlContent;
        return body
    return 'Ping!'

@app.route('/rpc/releaseTicket.action')
def releaseTicket():
    salt = ''
    if request.method == 'POST':
        salt = request.form.get('salt')
    if request.method == 'GET':
        salt = request.args.get('salt')

    if salt == None or salt == '':
        return 'error!'
    else:
        xmlContent = '<ReleaseTicketResponse><message></message><responseCode>OK</responseCode><salt>' + salt + '</salt></ReleaseTicketResponse>'
        xmlSignature = rsasign.sign(xmlContent)
        body = '<!-- ' + xmlSignature + ' -->\n' + xmlContent;
        return body
    return 'releaseTicket!'

@app.route('/rpc/obtainTicket.action')
def obtainTicket():
    salt=''
    username = ''
    if request.method == 'POST':
        salt = request.form.get('salt')
        username = request.form.get('userName')
    if request.method == 'GET':
        salt = request.args.get('salt')
        username = request.args.get('userName')
    prolongationPeriod = "607875500";
    if salt ==None or salt =='' or username ==None or username =='':
        return 'error!'
    else:
        xmlContent = '<ObtainTicketResponse><message></message><prolongationPeriod>' + prolongationPeriod + '</prolongationPeriod><responseCode>OK</responseCode><salt>' + salt + '</salt><ticketId>1</ticketId><ticketProperties>licensee=' + username + '\tlicenseType=0\t</ticketProperties></ObtainTicketResponse>'
        xmlSignature = rsasign.sign(xmlContent)
        body = '<!-- ' + xmlSignature + ' -->\n' + xmlContent;
        return body
    return 'obtainTicket!'


if __name__ == '__main__':
    app.run()
